<template>
  <span>
    <el-dialog
      :visible.sync="visible"
      :width="dialogWidth"
      title="查看文章"
      center
      :z-index="100006"
      modal-append-to-body
      :close-on-click-modal="false"
      class="bg-white rounded-xl shadow-2xl transform transition-all duration-300"
    >
    <div class="flex-col" style="max-height: 700px;">
      <div class="flex-1 overflow-auto">
        <div class="text-bold text-center" style="margin-bottom: 10px;">{{ dataItem.title }}</div>
        <div v-html="dataItem.contents" id="viewArticeContent" ></div>
      </div>
      <el-divider/>
      <div class="flex-row justify-center align-center flex-wrap gap-2">
        <el-button type="primary" size="small" @click="copyContents('title')">复制标题</el-button>
        <el-button type="primary" size="small" @click="copyContents('content')">复制内容</el-button>
        <el-button type="primary" size="small" @click="convertImagesToProy">图片地址替换代理地址</el-button>
        <el-button type="primary" size="small" @click="() => imageCollageVisible = true">设置封面</el-button>
        <el-button type="success" size="small" @click="downCover(dataItem.id, dataItem.title)">下封面</el-button>
        <!--        <el-button type="primary" size="small" @click="convertImagesToBase64">图片转base64</el-button>-->
      </div>
    </div>
  </el-dialog>

    <ImageCollage :visible.sync="imageCollageVisible" :articleId="dataItem.id"/>
  </span>
</template>
<script>
import html2canvas from "html2canvas";
import {updateCoverUrl, upload} from "@/api/imgManage/writeArticles";
import { encryptByDES, strToBase64 } from '@/utils/encryUtils'
export default {
  components: {
    ImageCollage: () => import('./ImageCollage')
  },
  props: {
    item: {}
  },
  data(){
    return {
      imageCollageVisible: false,
      visible: false,
      dataItem: {},
      screenshotHeight: 150,
      dialogWidth: '40%',
      isMobile: false,
    }
  },

  methods: {
    async init(dataItem){
      this.visible = true
      if(dataItem){
        this.$set(this,'dataItem', dataItem)
        await this.$nextTick()
        // this.convertImagesToProy()
      }
      if(this.item){
        this.dataItem = this.item
      }
    },
    checkDevice() {
      const width = window.innerWidth;
      const height = window.innerHeight;
      const screenInfo = {
        width,
        height,
        isMobile: width < 768
      };

      // 方法2: 通过User-Agent判断
      const userAgent = navigator.userAgent.toLowerCase();
      const isMobileByUA =
        userAgent.indexOf('mobile') !== -1 ||
        userAgent.indexOf('android') !== -1 ||
        userAgent.indexOf('iphone') !== -1 ||
        userAgent.indexOf('ipad') !== -1;

      // 综合两种判断结果
      this.isMobile = screenInfo.isMobile || isMobileByUA;
    },
    encryptData(data) {
      let data2 = encryptByDES(data)
      return strToBase64(data2)
    },
    convertImagesToProy(){
      this.$modal.loading("正在转换中，请稍候...");
      const baseUrl = this.$config.urlFormat('/proxy')
      const imgElements = document.querySelectorAll('#viewArticeContent img');
      for (const img of imgElements) {
        let imgUrl = img.src;
        if (!imgUrl.startsWith(this.$config.APIURL)) {
          imgUrl = `${baseUrl}&url=${this.encryptData(imgUrl)}`
          img.src = imgUrl
        }
      }
      this.$modal.closeLoading()
    },
    async convertImagesToBase64() {
      try {
        this.$modal.loading("正在转换中，请稍候...");
        // 获取所有图片元素
        const imgElements = document.querySelectorAll('#viewArticeContent img');
        // 处理所有图片
        for (const img of imgElements) {
          let imgUrl = img.src;
          // 跳过data:开头的图片（已经是base64格式）
          if (imgUrl.startsWith('data:')) {
            console.log('图片已经是Base64格式:', imgUrl.substring(0, 50) + '...');
            continue;
          }

          // 请求图片资源（处理跨域问题）
          const response = await fetch(imgUrl);
          if (!response.ok) {
            throw new Error(`图片请求失败: ${response.status} ${response.statusText}`);
          }

          // 将图片Blob转换为Base64
          const blob = await response.blob();
          const base64Url = await new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onloadend = () => resolve(reader.result);
            reader.onerror = reject;
            reader.readAsDataURL(blob);
          });

          // 替换图片的src为Base64格式
          img.src = base64Url;
          console.log('图片已成功转换为Base64:', img.alt);
        }
        console.log('所有图片转换完成');
        this.$modal.closeLoading()
        return true;
      } catch (error) {
        console.error('图片转换过程中发生错误:', error);
        return false;
      }
    },
    async copyContents(type) {
      try {
        let htmlContent, plainText;
        if (type === 'title') {
          // 复制标题逻辑保持不变
          htmlContent = `<div class="text-bold text-center">${this.dataItem.title}</div>`;
          plainText = this.dataItem.title;
        } else {
          // 复制内容改为获取id为viewArticeContent的元素内容
          const contentElement = document.getElementById('viewArticeContent');
          if (!contentElement) {
            this.$message.error('未找到文章内容元素');
            return;
          }
          htmlContent = contentElement.innerHTML;
          plainText = this.stripHtml(htmlContent);
        }

        const clipboardItem = new ClipboardItem({
          'text/html': new Blob([htmlContent], { type: 'text/html' }),
          'text/plain': new Blob([plainText], { type: 'text/plain' })
        });

        await navigator.clipboard.write([clipboardItem]);
        this.$message.success(`${type === 'title' ? '标题' : '内容'}已复制到剪贴板`);
      } catch (error) {
        console.error('复制失败:', error);
        this.$message.error('复制失败，请重试');
      }
    },
    // 辅助方法：从HTML中提取纯文本
    stripHtml(html) {
      const temp = document.createElement('div');
      temp.innerHTML = html;
      return temp.textContent || temp.innerText || '';
    },
    downCover(id, title,isDown = true) {
      return new Promise((resolve, reject) => {
        const refs = document.getElementById(id)
        this.$modal.loading("正在截图中，请稍候...");

        // 替换所有图片的URL为你的代理URL
        const replaceImagesWithProxy = () => {
          const baseUrl = this.$config.urlFormat('/proxy')
          let images = refs.querySelectorAll('img');
          const domain = window.location.origin;
          console.log('domain', domain)
          images.forEach( img => {
            if (img.src && img.src.startsWith('http') && !img.src.startsWith(domain) && !img.dataset.proxyConverted && !img.src.indexOf('/proxy')) {
              img.src = `${baseUrl}&url=${encodeURIComponent(img.src)}`
              // 设置成已转换
              img.dataset.proxyConverted = 'true';
            }
          });
        };
        replaceImagesWithProxy();

        setTimeout(() => {
          html2canvas(refs, {
            scale: 4,
            useCORS: true,
            allowTaint: true,
            height: this.screenshotHeight || 200
          }).then(canvas => {
            // 获取原始图像数据
            const originalImage = new Image();
            originalImage.src = canvas.toDataURL("image/png");

            // 创建新的2.35:1画布
            originalImage.onload = () => {
              // 目标比例2.35:1
              const targetRatio = 2.35;
              const originalRatio = canvas.width / canvas.height;

              // 创建新画布
              const newCanvas = document.createElement('canvas');
              const ctx = newCanvas.getContext('2d');

              if (originalRatio < targetRatio) {
                // 原图比例小于2.35:1（更"高"），添加左右填充
                newCanvas.width = canvas.height * targetRatio;
                newCanvas.height = canvas.height;

                // 绘制白色背景
                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, newCanvas.width, newCanvas.height);

                // 计算居中位置
                const offsetX = (newCanvas.width - canvas.width) / 2;

                // 绘制原始图像
                ctx.drawImage(
                  originalImage,
                  offsetX, 0,
                  canvas.width, canvas.height
                );
              } else {
                // 原图比例大于等于2.35:1（更"宽"），等比缩放
                newCanvas.width = canvas.width;
                newCanvas.height = canvas.width / targetRatio;

                // 计算居中位置
                const offsetY = (newCanvas.height - canvas.height) / 2;

                // 绘制白色背景
                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, newCanvas.width, newCanvas.height);

                // 绘制原始图像
                ctx.drawImage(
                  originalImage,
                  0, offsetY,
                  canvas.width, canvas.height
                );
              }
              // 保存调整后的图像并下载
              this.coverImgUrl = newCanvas.toDataURL("image/png");

              if(isDown){
                this.downImg(this.coverImgUrl, title);
              }

              // 上传图像
              this.uploadImage(this.coverImgUrl, title).then(async response => {
                console.log('上传成功:', response);
                // 可以在这里处理上传成功后的逻辑
                this.$message.success('封面上传成功');

                await updateCoverUrl({ id: id, coverUrl: response.url})

                this.$modal.closeLoading();

                resolve()
              }).catch(error => {
                console.error('上传失败:', error);
                this.$message.error('封面上传失败');
                this.$modal.closeLoading();
                reject()
              });

            };
          }).catch(e => {
            console.error(e)
            this.$modal.closeLoading()
          });
        },1000)
      });
    },
    downImg(imgUrl, fileName) {
      console.log('fileName ', fileName)
      const link = document.createElement('a');
      link.href = imgUrl;
      const timestamp = new Date().getTime();
      link.download = fileName ? `${fileName}.png` : `封面图_${timestamp}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 将DataURL转换为Blob对象
    dataURLToBlob(dataURL) {
      const arr = dataURL.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);

      while(n--){
        u8arr[n] = bstr.charCodeAt(n);
      }

      return new Blob([u8arr], {type: mime});
    },

    // 上传图像到服务器
    async uploadImage(dataURL, title) {
      try {
        // 将DataURL转换为Blob
        const blob = this.dataURLToBlob(dataURL);

        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', blob, `${title}.png`);
        // 发送请求到后端
        const response = await upload(formData);
        console.log('uploadResponse ', response)
        return response;
      } catch (error) {
        console.error('上传过程中出错:', error);
        throw error;
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkDevice);
  },
  mounted() {
    this.checkDevice()
    window.addEventListener('resize', this.checkDevice);

    if(this.isMobile){
      this.dialogWidth = '90%'
    }
  }
}
</script>
<style scoped lang="scss">
.text-center{
  font-size: 19px;
  text-align: center;
}
</style>
